<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', '管理员列表']" />
    <a-card class="general-card" title="管理员列表">
      <formCom
        ref="formComDom"
        :option="option"
        :keyCount="state.keyCount"
        @serachFn="searchFn"
      />
      <div class="right-btn">
        <el-button plan type="primary" @click="actionFn('add', {})"
          >新增管理员</el-button
        >
      </div>
      <kxTable
        :table-data="list"
        :column-list="columnList"
        border
        :loading="listLoading"
      >
        <template #options="{ row }">
          <el-button link plan type="danger" @click="actionFn('del', row)"
            >删除</el-button
          >
          <el-button link plan type="info" @click="actionFn('reset', row)"
            >重置密码</el-button
          >
        </template>
      </kxTable>
      <div class="pagination">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next, total"
          @current-change="getList"
        />
      </div>
    </a-card>

    <el-dialog v-model="showAddModal" title="新增管理员" width="500">
      <formCom
        ref="formComDom2"
        :option="option2"
        :keyCount="state.keyCount"
        @submitFn="addAdmin"
        @cancleFn="closeDialog"
      />
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import {
    resetPasswordApi,
    adminAddApi,
    adminDelApi,
    adminListApi,
  } from '@/utils/apiConfig';
  import { useList } from '@/use/index';
  import { useUserStore } from '@/store';
  import { storeToRefs } from 'pinia';
  import { setDeptFormatter } from '@/utils/util';
  const deptList = setDeptFormatter();

  const userStore = useUserStore();
  const { account } = storeToRefs(userStore);
  console.log('account', account.value);
  const {
    searchForm,
    list,
    listLoading,
    total,
    currentPage,
    pageSize,
    getList,
    handleSearch,
    resetSearch,
  } = useList(adminListApi);
  import md5 from 'md5';
  if (!searchForm.value) {
    searchForm.value = {
      account: account.value, // 与后端搜索参数一致
    } as any;
  }
  const router = useRouter();
  const route = useRoute();
  const {} = route.query;
  const state = reactive({
    keyCount: 1,
  });
  const option = reactive({
    labelWidth: '80px',
    isBetween: false, //false = float 布局
    position: 'left',
    formList: [
      {
        label: '账号名称',
        val: '',
        field: 'account',
        type: 'input',
        width: '340px',
        rightMargin: true,
      },
    ],
    showSreach: true, //是否显示搜索按钮
  });
  const option2 = reactive({
    labelWidth: '80px',
    isBetween: false, //false = float 布局
    position: 'left',
    formList: [
      {
        label: '账号',
        val: '',
        field: 'account',
        type: 'input',
        width: '100%',
        require: true,
        maxLength: 100,
      },
      {
        label: '密码',
        val: '',
        field: 'password',
        type: 'input',
        width: '100%',
        require: true,
      },
      {
        label: '部门编号',
        val: '',
        field: 'deptNo',
        type: 'treeSelect',
        width: '100%',
        chooseList: deptList,
      },
    ],
    showSubmit: true,
  });

  const columnList = reactive([
    {
      label: '账号',
      prop: 'account',
      minWidth: '120px',
    },
    {
      label: '时间',
      prop: 'createTime',
      minWidth: '120px',
    },
    {
      label: '身份',
      prop: 'identity',
      minWidth: '120px',
    },
    {
      label: '部门名称',
      prop: 'deptName',
      minWidth: '120px',
    },
    {
      label: '创建人',
      prop: 'createUser',
      minWidth: '120px',
    },

    {
      slot: 'operation',
      width: '160',
      label: '操作',
      prop: 'options',
      notooltip: true,
      fixed: 'right',
    },
  ]);
  function inits() {}
  function searchFn(obj: any) {
    console.log('searchFn', obj);
    searchForm.value = {
      account: obj.account,
    };
    getList();
  }
  const showAddModal = ref(false);

  function actionFn(type: string, item: any) {
    switch (type) {
      case 'add':
        showAddModal.value = true;
        break;
      case 'del':
        console.log(item.departmentName);
        ElMessageBox.confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            console.log('del-api');
            adminDelApi({ addPath: item.account })
              .then((res) => {
                console.log('del-admin-res', res);
                getList();
                ElMessage({
                  message: '删除管理员成功',
                  type: 'success',
                });
              })
              .catch((err) => {
                console.log('del-admin-err', err);
              });
          })
          .catch(() => {});
        break;
      case 'reset':
        ElMessageBox.prompt('请输入新密码', '重置密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          inputType: 'text',
          inputPlaceholder: '请输入新密码',
        })
          .then(({ value }) => {
            console.log('reset-api', item.account, value);
            resetPasswordApi({
              addPath: item.account,
              newPassword: md5(value).toUpperCase(),
            })
              .then((res) => {
                console.log('reset-password-res', res);
                getList();
                ElMessage({
                  message: '重置密码成功',
                  type: 'success',
                });
              })
              .catch((err) => {
                console.log('reset-password-err', err);
              });
          })
          .catch(() => {});
        break;

      default:
        break;
    }
  }

  function addAdmin(obj: any) {
    console.log('add', obj);

    adminAddApi({ ...obj, password: md5(obj.password).toUpperCase() })
      .then((res) => {
        console.log('add-admin-res', res);
        showAddModal.value = false;
        getList();
        ElMessage({
          message: '新增管理员成功',
          type: 'success',
        });
      })
      .catch((err) => {
        console.log('add-admin-err', err);
      });
  }
  function closeDialog() {
    console.log('closeDialog');
    showAddModal.value = false;
  }
  function handleAddSubmit() {
    // 这里写你的新增管理员 API 调用
    // await api.addAdmin(addForm.value)
    showAddModal.value = false;
  }
  onMounted(() => {
    inits();
    getList();
    // adminListApi({
    //   page: 0,
    //   size: 0,
    //   account: 'admin',
    // });
  });
</script>
<style lang="less" scoped>
  .container {
    padding: 20px;
  }
</style>
